//
//  RegexHelper.swift
//  TuJiaMerchant
//
//  Created by 何海涛 on 16/1/7.
//  Copyright © 2016年 途家. All rights reserved.
//

import Foundation

public class Regex {
    /// 电子邮件
    public static let EmailPattern = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$"
    /// 手机号
    public static let MobilePattern = "^\\d{11}$"
    /// 手机&座机 放宽
    public static let MobileAndPhone = "^\\d{7,13}$"
    /// 中国身份证号
    public static let IDCardPattern = "^(\\d{15}|\\d{17}[0-9xX])$"
    /// 汉字
    public static let ChinesePattern = "^[\\u4e00-\\u9fa5]{0,}$"
    /// 域名
    public static let DomainPattern = "[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(/.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+/.?"
    
    let internalExpression: NSRegularExpression?
    let pattern: String
    
    public init(_ pattern: String) {
        self.pattern = pattern
        do {
            try self.internalExpression = NSRegularExpression(pattern: pattern, options: .caseInsensitive)
        } catch {
            fatalError("Error happened when trying to construct an Regular Expression, please check the pattern string.")
        }
    }
    
    public func test(_ input: String, options: NSRegularExpression.MatchingOptions = .anchored) -> Bool {
        return self.internalExpression?.firstMatch(in: input, options: options, range: NSMakeRange(0, input.count)) != nil
    }
}
